# =============================================================================
#'
#' @title Read Time Series
#'
#' @description Read GEOtop time series into data frame
#'
#' @details This function reads a GEOtop time series such as a meteo file or 
#' a result from file. The first column is considered date/time and converted to
#' POSIXct in UTC. 
#'
#' @param infile Full file name of the the GEOtop time series file to be read.
#' @param comment Option to return only the comment line(s) of a file. The 
#' default is FALSE and only the file data is returned. If several recovered 
#' file comments are read, they are all returned together.

#' @param duplicates.remove Optional vector [e.g., c(2,3,4)] of columns to 
#" consider as primary key during duplicates removal. The default value for
#' duplicates.remove is FALSE, preventing duplicate removal. Duplicate removal 
#' is recommended when a simulation has been recovered and possibly several
#' files exist for one type of output. Usual columns for duplicate removal are
#' Date, period, run, pointID.
#' @param env List that passes a number of default settings.
#' @export
#'
#' @return Returns a data frame. The first column, named "Date", is in POSIXct
#' and referenced to UTC. All other columns are numeric and have nodata 
#' indicated by NA. The nodata value used is set in SetEnv() and can be changed
#' manually. If a simulation has been recovered (possibly several times), files
#' written by recovered runs are also read and merged into one data frame. 
#'
#' @examples
#' meteo <- TimeSeriesRead("./data/meteo0001.txt", env = SetEnv())
#'
#' @author Stephan Gruber <stephan.gruber@@carleton.ca>
#'
# =============================================================================


#enable reading of recovered data from several files
TimeSeriesRead <- function(infile, comment = FALSE,
                           duplicates.remove = FALSE, env = SetEnv()) {
  #read first file       
  data <- TimeSeriesReadOne(infile, comment = comment, env = env)

  #loop over possible recovery files
  filebase <- substr(infile, 1, nchar(infile) - nchar(env$textext))
  for (rec in 1:999) {
    recfile <- paste(filebase, env$sufxrec, 
                     formatC(rec, width = nchar(env$textext), flag = "0"), 
                     env$textext, sep = "")
    if (file.exists(recfile)) {
      rec  <- TimeSeriesReadOne(recfile, comment = comment, env = env)
      data <- rbind(data, rec)
    } else break
  }
  
  #remove duplicated after merging files
  #this is necessary if writing is stopped by grid and files of
  #one episode (e.g., *_crec0004.txt) differ in length
  if (duplicates.remove[1] != FALSE) {
    ind <- duplicated(data[, duplicates.remove])
    data <- data[ind == FALSE,]
  }
  return(data)
}



